'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 联盟BOSS信息
 * @author sundbcn@gmail.com (sun debing)
 */

var moment = require('moment');
var mongoConnector = require('../libs/mongodb/mongoConnector');
/* jshint unused:false */
var unionBossSchema = require('../schemas/unionBossSchema');
var UnionBoss = mongoConnector().model('UnionBoss');
var constantUtil = require('../util/constantUtil.js');

/**
 * 按ID查询
 */
module.exports.findById = function (union_id, callback) {
    function cb(err, schema) {
        if (!err && !!schema) {
            if (schema.curr_boss_id === 0) {
                console.log('---------重置联盟BOSS---------');
                schema.resetBoss();
            }
        }
        callback(err, schema);
    }

    function afterCreate(err, schema) {
        cb(err, schema);
    }

    function afterFindOne(err, schema) {
        if (!!err) {
            return cb(err);
        }
        if (!!schema) {
            return cb(null, schema);
        } else {
            UnionBoss.create({
                union_id: union_id
            }, afterCreate);
        }
    }

    UnionBoss.findOne({
        union_id: union_id
    }, afterFindOne);
};

// 锁定联盟BOSS
module.exports.lockBoss = function (union_id, role_id, role_name, cb) {
    var now_tm = moment().unix();
    var union_check = {
        union_id: union_id
    };
    var lock_status = {
        $or: [
            {
                lock_role_id: 0
            },
            {
                lock_role_id: role_id
            },
            {
                lock_end_tm: {
                    $lt: now_tm
                }
            }
        ]
    };
    var where = {
        $and: [union_check, lock_status]
    };

    var war_time = constantUtil.value('war_time');

    UnionBoss.update(where, {
        $set: {
            lock_role_id: role_id,
            lock_role_name: role_name,
            lock_end_tm: now_tm + war_time + 30
        }
    }, function (err, numberAffected) {
        cb(err, numberAffected.n > 0);
    });
};

// 解锁联盟BOSS
module.exports.unLockBoss = function (union_id, cb) {
    UnionBoss.update({
        union_id: union_id
    }, {
        $set: {
            lock_role_id: 0,
            lock_role_name: '',
            lock_end_tm: 0
        }
    }, cb);
};

// 查询BOSS信息
module.exports.find = function (where, callback) {
    UnionBoss.find(where, callback);
};
